/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.umeox.watch.moto.dataservice.services;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;

import com.umeox.watch.moto.apiclient.http.response.WaasResponse;
import com.umeox.watch.moto.dataservice.base.AppExecutors;


public abstract class NetworkTask<DbResultType, ResponseType> {
    private final AppExecutors appExecutors;

    @MainThread
    protected NetworkTask(AppExecutors appExecutors) {
        this.appExecutors = appExecutors;
        this.appExecutors.diskIO().execute(() -> {
            DbResultType dbSource = loadFromDb();
            this.appExecutors.mainThread().execute(() -> {
                if (shouldFetch(dbSource)) {
                    fetchFromNetwork(dbSource);
                } else {
                    onSuccess(dbSource);
                }
            });
        });
    }

    private void fetchFromNetwork(final DbResultType dbSource) {
        onLoading();
        appExecutors.networkIO().execute(() -> {
            WaasResponse response = createCall();
            if (response != null && response.isSuccessful()) {
                ResponseType responseData = processResponse(response);
                appExecutors.diskIO().execute(() -> {
                    DbResultType temp = saveCallResult(responseData);
                    appExecutors.mainThread().execute(() -> onSuccess(temp));
                });
            } else {
                appExecutors.mainThread().execute(() -> onFetchFailed(dbSource));
            }
        });
    }

    @MainThread
    protected void onFetchFailed(DbResultType data) {
    }

    @MainThread
    public void onLoading() {
    }

    @MainThread
    public void onSuccess(@Nullable DbResultType data) {
    }

    @WorkerThread
    protected ResponseType processResponse(WaasResponse response) {
        return (ResponseType) response.getData();
    }

    @WorkerThread
    protected abstract DbResultType saveCallResult(ResponseType item);

    @MainThread
    protected boolean shouldFetch(@Nullable DbResultType data) {
        return data == null;
    }


    @WorkerThread
    protected DbResultType loadFromDb() {
        return null;
    }

    @WorkerThread
    protected abstract WaasResponse createCall();
}
